package lt.marsrutai.mobile.android.activity;

import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.billing.BillingService;
import lt.marsrutai.mobile.android.billing.BillingService.RequestPurchase;
import lt.marsrutai.mobile.android.billing.BillingService.RestoreTransactions;
import lt.marsrutai.mobile.android.billing.Consts;
import lt.marsrutai.mobile.android.billing.Consts.PurchaseState;
import lt.marsrutai.mobile.android.billing.Consts.ResponseCode;
import lt.marsrutai.mobile.android.billing.PurchaseObserver;
import lt.marsrutai.mobile.android.billing.ResponseHandler;
import lt.marsrutai.mobile.android.manager.ActivityManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import com.google.analytics.tracking.android.EasyTracker;

public class DonationsActivity extends BaseActivity {
    
    public static final String PRODUCT_ID_LARGE = "marsrutai_android_donation_large";
    public static final String PRODUCT_ID_MEDIUM = "marsrutai_android_donation_medium";
    public static final String PRODUCT_ID_SMALL = "marsrutai_android_donation_small";

    private ActivityManager manager;    
    private BillingService billingService;
    private DonationsPurchaseObserver purchaseObserver;



    @Override
    public void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);
        manager = new ActivityManager(this, R.string.no_billing_message);
        setContentView(R.layout.progress_spinner);
        manager.showDownloadLoadingBar();

        // Debug
        purchaseObserver = new DonationsPurchaseObserver(new Handler());
        ResponseHandler.register(purchaseObserver);
        billingService = new BillingService();
        billingService.setContext(this);
        billingService.checkBillingSupported(Consts.ITEM_TYPE_INAPP);
    }
    
    private void initialize() {
        setContentView(R.layout.donations_layout);
        setupButtons();
    }
    
    private void setupButtons() {
        findViewById(R.id.donations_large).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DonationsActivity.this.billingService.requestPurchase(PRODUCT_ID_LARGE, Consts.ITEM_TYPE_INAPP, null);                 
            }
        });
        
        findViewById(R.id.donations_medium).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DonationsActivity.this.billingService.requestPurchase(PRODUCT_ID_MEDIUM, Consts.ITEM_TYPE_INAPP, null);                 
            }
        });
        
        findViewById(R.id.donations_small).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DonationsActivity.this.billingService.requestPurchase(PRODUCT_ID_SMALL, Consts.ITEM_TYPE_INAPP, null);                 
            }
        });
    }
    
    
    private void notifyDonationAccepted() {
        // We've got a successful payment!
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.ic_cup).setTitle(getString(R.string.donations_accepted_title))
            .setMessage(getString(R.string.donations_accepted_message)).setCancelable(false)
            .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    DonationsActivity.this.finish();
                }
            });
        builder.create().show();
        
    }
    
    
    @Override
    protected void onStart() {
        super.onStart();
        ResponseHandler.register(purchaseObserver);        
    }

    @Override
    protected void onStop() {
        super.onStop();
        ResponseHandler.unregister(purchaseObserver);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        billingService.unbind();
    }
    
    @Override
    public NavMenuData getNavMenuData() {        
        return new NavMenuData(new String[] { this.getString(R.string.donations_title) } );        
    }


    
    private class DonationsPurchaseObserver extends PurchaseObserver {
        
        private static final String TAG = "PurchaseObserver";
        
        public DonationsPurchaseObserver(Handler handler) {
            super(DonationsActivity.this, handler);
        }

        @Override
        public void onBillingSupported(boolean supported, String type) {
            if (Consts.DEBUG) {
                Log.i(TAG, String.format("supported: %s %s", supported, type));
            }
            // Track for debug purposes
            EasyTracker.getTracker().trackEvent("billing", 
                "onBillingSupported",
                String.format("onBillingSupported(): %s %s", supported, type),
                0L
            );
            
            if (supported && (type == null || type.equals(Consts.ITEM_TYPE_INAPP))) {
                // Supported - initialize UI                
                DonationsActivity.this.initialize();                
            } 
            else {
                // Unsupported - show message and go back
                manager.runOnUiThread(manager.errorRes);
            }
        }

        @Override
        public void onPurchaseStateChange(PurchaseState purchaseState, String itemId,
                long purchaseTime, String developerPayload) {
            if (Consts.DEBUG) {
                Log.i(TAG, "onPurchaseStateChange(): " + itemId + " " + purchaseState);
            }
            // Track for debug purposes
            EasyTracker.getTracker().trackEvent("billing", 
                "onPurchaseStateChange",
                "onPurchaseStateChange() itemId: " + itemId + " - " + purchaseState,
                0L
            );
            
            if (purchaseState == PurchaseState.PURCHASED) {
                // Purchased
                DonationsActivity.this.notifyDonationAccepted();
            }
        }

        @Override
        public void onRequestPurchaseResponse(RequestPurchase request,
                ResponseCode responseCode) {
            if (Consts.DEBUG) {
                Log.d(TAG, request.mProductId + ": " + responseCode);
            }
            // Track for debug purposes
            EasyTracker.getTracker().trackEvent("billing", 
                "onRequestPurchaseResponse",
                "onRequestPurchaseResponse(): " + request.mProductId + " - " + responseCode,
                0L
            );
            
            if (responseCode == ResponseCode.RESULT_OK) {
                if (Consts.DEBUG) {
                    Log.i(TAG, "purchase was successfully sent to server");
                }                
            } else if (responseCode == ResponseCode.RESULT_USER_CANCELED) {
                if (Consts.DEBUG) {
                    Log.i(TAG, "user canceled purchase");
                }                
            } else {
                if (Consts.DEBUG) {
                    Log.i(TAG, "purchase failed");
                }                
            }
        }

        @Override
        public void onRestoreTransactionsResponse(RestoreTransactions request,
                ResponseCode responseCode) {
            if (responseCode == ResponseCode.RESULT_OK) {
                if (Consts.DEBUG) {
                    Log.d(TAG, "completed RestoreTransactions request");
                }
            } else {
                if (Consts.DEBUG) {
                    Log.d(TAG, "RestoreTransactions error: " + responseCode);
                }
            }
        }
    }

}